package com.pn.controller;

import com.pn.entity.*;
import com.pn.page.Page;
import com.pn.service.InStoreService;
import com.pn.service.PurchaseService;
import com.pn.service.StoreService;
import com.pn.utils.TokenUtils;
import com.pn.utils.WarehouseConstants;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/purchase")
public class PurchaseController {
    @Resource
    private PurchaseService purchaseService;
    @Resource
    private StoreService storeService;
    @Resource
    private TokenUtils tokenUtils;
    @Resource
    private InStoreService inStoreService;

    //添加采购单
    @RequestMapping("/purchase-add")
    public Result addPurchase(@RequestBody Purchase purchase){
        int result = purchaseService.addPurchase(purchase);
        if(result > 0){
            return Result.ok("采购单添加成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS,"采购单添加失败！");
    }

    //查询所有仓库
    @RequestMapping("/store-list")
    public Result findAllStore(){
        List<Store> allStore = storeService.findAllStore();
        return Result.ok(allStore);
    }

    //分页查询入库单
    @RequestMapping("/purchase-page-list")
    public Result findPurchaseList(Purchase purchase, Page page){
        Page purchaseByPage = purchaseService.findPurchaseByPage(purchase, page);
        return Result.ok(purchaseByPage);
    }

    //删除采购单记录
    @RequestMapping("/purchase-delete/{bid}")
    public Result removePurchaseByBid(@PathVariable Integer bid){
        Result result = purchaseService.removePurchaseByBid(bid);
        return result;
    }

    //更新采购单数据
    @RequestMapping("/purchase-update")
    public Result modifyPurchaseNumByBid(@RequestBody Purchase purchase){
        Result result = purchaseService.modifyPurchaseNumByBid(purchase);
        return result;
    }

    //插入入库单记录
    @RequestMapping("/in-warehouse-record-add")
    public Result addInStore(@RequestBody Purchase purchase, @RequestHeader(value = WarehouseConstants.HEADER_TOKEN_NAME) String token){
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        int userId = currentUser.getUserId();
        InStore inStore = new InStore();
        inStore.setStoreId(purchase.getStoreId());
        inStore.setProductId(purchase.getProductId());
        inStore.setCreateBy(userId);
        inStore.setInNum(purchase.getFactBuyNum());
        Result result = inStoreService.addInStore(inStore, purchase.getBuyId());
        return result;
    }



}
